package com.zenithmind.coding.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zenithmind.coding.mapper.TestCaseMapper;
import com.zenithmind.coding.pojo.entity.TestCase;
import com.zenithmind.coding.service.TestCaseService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 测试用例服务实现类
 * 
 * @author ZenithMind Team
 * @since 2025-01-09
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TestCaseServiceImpl extends ServiceImpl<TestCaseMapper, TestCase> implements TestCaseService {

    private final TestCaseMapper testCaseMapper;

    @Override
    public List<TestCase> getTestCasesByProblemId(String problemId, Boolean includePrivate) {
        LambdaQueryWrapper<TestCase> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(TestCase::getProblemId, problemId);
        wrapper.eq(TestCase::getIsEnabled, 1);
        
        if (!includePrivate) {
            wrapper.eq(TestCase::getIsPublic, 1);
        }
        
        wrapper.orderByAsc(TestCase::getSortOrder, TestCase::getCaseNumber);
        
        return list(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean createTestCase(TestCase testCase) {
        // 设置输入输出数据大小
        if (testCase.getInputData() != null) {
            testCase.setInputSize((long) testCase.getInputData().getBytes().length);
        }
        if (testCase.getExpectedOutput() != null) {
            testCase.setOutputSize((long) testCase.getExpectedOutput().getBytes().length);
        }
        
        return save(testCase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateTestCase(TestCase testCase) {
        // 更新输入输出数据大小
        if (testCase.getInputData() != null) {
            testCase.setInputSize((long) testCase.getInputData().getBytes().length);
        }
        if (testCase.getExpectedOutput() != null) {
            testCase.setOutputSize((long) testCase.getExpectedOutput().getBytes().length);
        }
        
        return updateById(testCase);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteTestCase(String id) {
        return removeById(id);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Integer batchCreateTestCases(List<TestCase> testCases) {
        int successCount = 0;
        for (TestCase testCase : testCases) {
            try {
                if (createTestCase(testCase)) {
                    successCount++;
                }
            } catch (Exception e) {
                log.error("创建测试用例失败", e);
            }
        }
        return successCount;
    }
}
